package com.example.quce.controller;

import cn.hutool.core.bean.BeanUtil;
import com.example.quce.bo.QuizSaveBO;
import com.example.quce.common.R;
import com.example.quce.entity.Quiz;
import com.example.quce.entity.User;
import com.example.quce.mapper.QuizMapper;
import com.example.quce.mapper.UserMapper;
import com.example.quce.service.IQuizService;
import com.example.quce.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/quiz")
@RequiredArgsConstructor
public class QuizController {

    @Autowired
    QuizMapper quizMapper;
    @Autowired
    UserMapper userMapper;


    private final IUserService userService;
    private final IQuizService quizService;



    // 读取测试结果
    @GetMapping("/getByUserId/{userId}")
    public R getByUserId(@PathVariable int userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return R.error("用户不存在");
        }
        // 用户存在
        List<Quiz> list = quizService.lambdaQuery().eq(Quiz::getUserId, userId).orderByDesc(Quiz::getCreateTime).list();
        return R.ok(list);
    }

    // 读取测试结果
    @GetMapping("/selectByUserId/{userId}")
    public R selectByUserId(@PathVariable int userId) {
        User user = this.userMapper.selectUserById(userId);
        if (user == null) {
            return R.error("用户不存在");
        }
        // 用户存在
        List<Quiz> list = this.quizMapper.selectByUserId(userId);
        return R.ok(list);
    }

    // 保存测试结果
    @PostMapping("/saveQuiz")
    public R saveQuiz(@RequestBody QuizSaveBO request) {
        User user = userService.getById(request.getUserId());
        if (user == null) {
            return R.error("用户不存在");
        }
        Quiz quiz = BeanUtil.copyProperties(request, Quiz.class);
        quiz.setCreateTime(System.currentTimeMillis());
        boolean save = quizService.save(quiz);
        return R.ok(save);
    }
}
